<?php

namespace App\Http\Middleware\Admin\v1;

use Closure;
use App\Models\ApiKey;
use App\Services\Utils\Guard;
use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;

class CustomerCreateApiKey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Guard::customer();
        if($request->type == 0){ //测试方案
            $api = ApiKey::where('customer_id', $user['id'])->whereNull('type')->first();
            if (isset($api)) {  //是否已存在测试ApiKey
                throw new ApiException(ApiErrCode::TEST_API_KEY_ONLY_ONE, trans('middleware.api_key.test_api_key_only_one'));
            }
        } elseif(!in_array($request->type, [0,1])) {    //用户只能创建测试和按次计费两种方案
            throw new ApiException(ApiErrCode::NOT_API_KEY_SCHEME_JURIS, trans('middleware.api_key.not_api_key_scheme_juris'));
        }
        $mid_params = ['customer_id' => $user->id];
        $request->attributes->add($mid_params);
        return $next($request);
    }
}
